package com.example.shop_2212.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.CodeEntityResult
import com.example.base.entity.LoginEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    //返回值
    val loginCodeSuccess = MutableLiveData<LoginEntityResult>()
    val loginCodeFail = MutableLiveData<String>()
    //调用接口--执行后台请求
    fun loginCode(captcha:String,phone:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map.put("captcha",captcha)
                map.put("phone",phone)
                loginCodeSuccess.value = apiServer.loginCode(mapToBody(map))
            }catch (e:Exception){
                //请求失败
                loginCodeFail.value = e.message
            }
        }
    }
    //返回值 --发送验证码
    val codeSuccess = MutableLiveData<CodeEntityResult>()
    val codeFail = MutableLiveData<String>()
    fun sendCode(phone:String){
        viewModelScope.launch {
            try {
                codeSuccess.value = apiServer.sendCode(phone)
            }catch (e:Exception){
                codeFail.value = e.message
            }
        }
    }
    //返回值 --密码登录
    val loginSuccess = MutableLiveData<LoginEntityResult>()
    val loginFail = MutableLiveData<String>()
    fun login(account:String,password:String,spread_spid:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map.put("account",account)
                map.put("password",password)
                map.put("spread_spid",0)
                loginSuccess.value = apiServer.login(mapToBody(map))
            }catch (e:Exception){
                loginFail.value = e.message
            }
        }
    }
}